package com.roc.web.action.ysb;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.AreaBean;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.service.IExcelService;
import com.roc.service.area.IAreaService;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;

/**
 * 云商宝交易统计信息
 * @author jjj
 *
 */
@Component
@Scope("prototype")
@Namespace("/ysbTermianlTransStatics")
public class YsbTermianlTransStaticsAction extends PaginationBaseAction{
	
	private static final long serialVersionUID = 1L;
	
	private Logger logger=LogManager.getLogger(YsbTermianlTransStaticsAction.class);
	@Autowired
	IPageService pagenitionService;
	@Autowired
	IAreaService areaService;
	@Autowired
	private IPowerInfoService powerInfoService;
	
	@Autowired
	private IExcelService excelService;
	private List<AreaBean> areaCodeList = new ArrayList<AreaBean>();
	private YsbTermianlTransStaticsSearchCondition searchCondition;
	
	private InputStream excelFile;
	
	
	@Action(value="init",results={ @Result(name="success",location="/pages/ysb/ysbTermianlTransStatics.jsp")})
	public String windControllStaJsp(){
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try{
		 if(op.getRoleType().equals(Role.OPERATORS_COMM.getCode())){
			  Map<String, String> map=powerInfoService.queryRealIdByOpId(op.getSuperiorId(), op.getRoleType(), op.getId(), op.getOrgCode());
	          String superRole= map.get("superRole");
	          String opRealId =map.get("opRealId");
	      	  Operators operator1 = powerInfoService.loadOperatorsById(new Long(opRealId));//分批终端序列号目的对象
	      	  op.setSuperiorId(operator1.getSuperiorId());
	          op.setRoleType(superRole);
	          op.setId(Long.valueOf(opRealId));
          }
        if(!("sdsyb".equals(op.getAccountNo())
        		||((op.getRoleType().equals(Role.AGENT.getCode())||op.getRoleType().equals(Role.O_MANAGER.getCode()))
        		&&op.getSuperiorId().toString().equals("40001"))||op.getRoleType().equals(Role.SYSTEM.getCode()))) {
        	addActionError("当前登录账号无权限访问!!!");
			return ERROR;
		}
		areaInf();
		}catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
			return ERROR;
		}
		return SUCCESS;
		}
	
	@Action(value="ysbTermianlTransStaticsQuery",results={@Result(name="success",location="/pages/ysb/ysbTermianlTransStatics.jsp")})
	public String queryWindControllSta(){
	
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			
		 if(op.getRoleType().equals(Role.OPERATORS_COMM.getCode())){
			  Map<String, String> map=powerInfoService.queryRealIdByOpId(op.getSuperiorId(), op.getRoleType(), op.getId(), op.getOrgCode());
	          String superRole= map.get("superRole");
	          String opRealId =map.get("opRealId");
	      	  Operators operator1 = powerInfoService.loadOperatorsById(new Long(opRealId));//分批终端序列号目的对象
	      	  op.setSuperiorId(operator1.getSuperiorId());
	          op.setRoleType(superRole);
	          op.setId(Long.valueOf(opRealId));
          }
		  if(!("sdsyb".equals(op.getAccountNo())
	        		||((op.getRoleType().equals(Role.AGENT.getCode())||op.getRoleType().equals(Role.O_MANAGER.getCode()))
	        		&&op.getSuperiorId().toString().equals("40001"))||op.getRoleType().equals(Role.SYSTEM.getCode()))) {
	        	addActionError("当前登录账号无权限访问!!!");
				return ERROR;
			}
    	areaInf();
		if(searchCondition==null){
			searchCondition=(YsbTermianlTransStaticsSearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new YsbTermianlTransStaticsSearchCondition();
			}
		}
		if(!op.getRoleType().equals(Role.SYSTEM.getCode())){
			searchCondition.setCode(op.getCompanyid());
		}
		
		//List<Object> params = new ArrayList<Object>();
		logger.info("查询条件,起始时间："+searchCondition.getStartingDate()+" 结束时间："+searchCondition.getEndDate());

			List<Object>  wcsList=new ArrayList<Object>();
			int rows =pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList = pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			}
			if(searchRsList!=null&&searchRsList.size()>0){
				Iterator<?> iterator=searchRsList.iterator();
				while (iterator.hasNext()) {
					Object[] obj=(Object[]) iterator.next();
					HashMap<String, String> map=new HashMap<String, String>();
					map.put("companyName", Constance.Null2EmptyTrim(obj[0]));
					map.put("realName", Constance.Null2EmptyTrim(obj[1]));
					map.put("transNum", Constance.Null2EmptyTrim(obj[3]));
					map.put("transAmt", Constance.Null2EmptyTrim(obj[4]));
					map.put("transDt", Constance.Null2EmptyTrim(obj[2]));
					wcsList.add(map);
			   }
			}
			getRequest().setAttribute("wcsList", wcsList);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			addActionMessage("当前条件下统计到【"+rows+"】条记录");
		} catch (Exception e) {
			logger.info("查询云商宝交易统计数据异常："+e);
		}
		return SUCCESS;
	}
	
	@Action(value = "ysbTermianlTransStaticsExcel", results = {
			@Result(name = "success", type = "stream", params = {
					"contentType", "application/vnd.ms-excel", "inputName",
					"excelFile", "contentDisposition",
					"attachment;filename=${excelName}.xls", "bufferSize",
					"1024*3" }),
			@Result(name = "error", location = "/pages/windControllSta/windControllStaJsp.jsp") })
	public String exportWindControllSta(){
		
		logger.info("导出云商宝交易统计excel开始");
		
		if(searchCondition==null){
			searchCondition=(YsbTermianlTransStaticsSearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new YsbTermianlTransStaticsSearchCondition();
			}
		}
		
	//	List<Object> params = new ArrayList<Object>();
		logger.info("导出条件,起始时间："+searchCondition.getStartingDate()+" 结束时间："+searchCondition.getEndDate());
		
		try {
			logger.info("转换后的时间格式："+new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyyMMdd").parse(searchCondition.getStartingDate())));
			/*params.add(new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyyMMdd").parse(searchCondition.getStartingDate())));
			params.add(new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyyMMdd").parse(searchCondition.getEndDate())));
			params.add(new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyyMMdd").parse(searchCondition.getStartingDate())));
			params.add(new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyyMMdd").parse(searchCondition.getEndDate())));
			*/
			int rows = pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList = pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()),rows);
			}
			
			logger.info("rows:" + rows + "    searchRsList.size():"
					+ searchRsList.size());
			/*List<Object>  wcsList=new ArrayList<Object>();
			if(searchRsList!=null&&searchRsList.size()>0){
				Iterator<?> iterator=searchRsList.iterator();
				while (iterator.hasNext()) {
					Object[] obj=(Object[]) iterator.next();
					HashMap<String, String> map=new HashMap<String, String>();
					map.put("companyName", Constance.Null2EmptyTrim(obj[0]));
					map.put("realName", Constance.Null2EmptyTrim(obj[1]));
					map.put("transNum", Constance.Null2EmptyTrim(obj[3]));
					map.put("transAmt", Constance.Null2EmptyTrim(obj[4]));
					map.put("transDt", Constance.Null2EmptyTrim(obj[2]));
					wcsList.add(map);
			   }
			}*/
			HSSFWorkbook work = excelService.ysbTermianlTransStaticsList(
					searchRsList, searchCondition.getStartingDate(),
					searchCondition.getEndDate());

			ByteArrayOutputStream output = new ByteArrayOutputStream();
			work.write(output);

			byte[] ba = output.toByteArray();
			excelFile = new ByteArrayInputStream(ba);
			output.flush();
			output.close();

			logger.info("导出云商宝交易统计excel结束");
		} catch (Exception e) {
			logger.info("导出云商宝交易统计数据异常："+e);
		}
		return SUCCESS;
	}
	
	public String areaInf(){
		try {
		    Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		    areaCodeList = areaService.queryAreaInfByOp(op);
		} catch (Exception e) {
			addActionError("加载机构失败，请联系客服人员");
			logger.error(e.getMessage(),e);
		}
		return SUCCESS;
	}
	
	public List<AreaBean> getAreaCodeList() {
		return areaCodeList;
	}

	public void setAreaCodeList(List<AreaBean> areaCodeList) {
		this.areaCodeList = areaCodeList;
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
		
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_QUERY_WIND_CONTROLL, searchCondition);
		
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (YsbTermianlTransStaticsSearchCondition)getSession().getAttribute(SEARCH_SESSION_QUERY_WIND_CONTROLL);
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE+"";
	}

	public YsbTermianlTransStaticsSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(YsbTermianlTransStaticsSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}
	
	public String getExcelName() {
		String excelName = "云商宝交易统计" + Constance.formateDate();

		try {
			excelName = new String(excelName.getBytes(), "ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			// e.printStackTrace();
			logger.info("生成excel名称失败了！");
		}

		return excelName;

	}

	
}
